<template>
    <div class="product-container layout-padding">
        <div class="mb15">
            <TableSearch :search="state.tableData.search" @search="onSearch" />

            <el-button size="default" type="success" class="ml10" @click="onOpenAddProduct('add')">
                <el-icon>
                    <ele-FolderAdd />
                </el-icon>
                新增产品
            </el-button>
        </div>


        <div class="product-padding layout-padding-view layout-padding-auto">
            <Table ref="tableRef" v-bind="state.tableData" class="product" @pageChange="onTablePageChange"
                @sortHeader="onSortHeader">

                <template v-slot:tableOperate="row">
                    <el-button size="small" text type="primary" @click="writeCosting(row.row)">
                        细则
                    </el-button>
                    <el-button size="small" text type="primary" @click="onOpenAddProduct('edit', row.row.id)">
                        编辑
                    </el-button>
                    <el-popconfirm title="确定删除吗？" @confirm="onTableDelRow(row.row)">
                        <template #reference>
                            <el-button size="small" text type="primary">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </Table>
        </div>
        <productDialog ref="productDialogRef" @refresh="getTableData()" />
    </div>
</template>

<script setup lang="ts" name="product">
import { defineAsyncComponent, reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useProductApi } from '/@/api/mainData/product';
import { getWeightCalculate } from '/@/utils/order';

// 引入 api 请求接口
const productApi = useProductApi();

// 引入组件
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const productDialog = defineAsyncComponent(() => import('./component/productDialog.vue'));

// 定义变量内容
const router = useRouter();
const tableRef = ref<RefType>();
const state = reactive<TableDemoState>({
    tableData: {
        // 列表数据（必传）
        data: [],
        // 表头内容（必传，注意格式）
        header: [
            { key: 'name', colWidth: '', title: '产品名称', type: 'text', isCheck: true },
            { key: 'plOne', colWidth: '', title: '一级品类', type: 'text', isCheck: true },
            { key: 'plTwo', colWidth: '', title: '二级品类', type: 'text', isCheck: true },
            { key: 'variantCodeOne', colWidth: '', title: '变体1', type: 'text', isCheck: true },
            { key: 'variantCodeTwo', colWidth: '', title: '变体2', type: 'text', isCheck: true },
            { key: 'vendorName', colWidth: '', title: '供货商', type: 'text', isCheck: true },
            { key: 'vendorProductTypeName', colWidth: '', title: '供货商产品类型', type: 'text', isCheck: true },
            { key: 'weightCalculateStr', colWidth: '', title: '计抛/计重', type: 'text', isCheck: true },
        ],
        // 配置项（必传）
        config: {
            total: 0, // 列表总数
            loading: true, // loading 加载
            isBorder: false, // 是否显示表格边框
            isSerialNo: true, // 是否显示表格序号
            isSelection: false, // 是否显示表格多选
            isOperate: true, // 是否显示表格操作栏
        },
        // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
        search: [
            { label: '产品名称', prop: 'name', placeholder: '支持模糊搜索', required: false, type: 'input', defaultVal: '' },
        ],
        // 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
        param: {
            pageNum: 1,
            pageSize: 10,
        },
        // 打印标题
        printName: '产品',
    },
});
const productDialogRef = ref();

//搜索
const onSearch = (data: EmptyObjectType) => {
    state.tableData.param = Object.assign({}, state.tableData.param, { ...data });
    tableRef.value.pageReset();
};


// 初始化列表数据
async function getTableData() {
    state.tableData.config.loading = true;
    const productData = await productApi.queryProductList(state.tableData.param);
    if (productData.data.length <= 0)
        return Promise.resolve(true);

    const newProductData: Product[] = productData.data.rows;
    const showProductData = [];
    if (undefined != newProductData) {
        for (const item of newProductData) {
            const weightCalculateStr = getWeightCalculate(item.weightCalculate);
            const tmp = { weightCalculateStr: weightCalculateStr };

            const showProductItem = { ...item, ...tmp };
            showProductData.push(showProductItem);
        }
    }

    state.tableData.data = showProductData;
    state.tableData.config.total = productData.data.total;
    setTimeout(() => {
        state.tableData.config.loading = false;
    }, 500);
};

// 打开编辑弹窗
const onOpenAddProduct = (type: string, productId?: number) => {
    productDialogRef.value.openDialog(type, productId);
};

// 删除当前项回调
async function onTableDelRow(row: EmptyObjectType) {
    const deleteItem = {
        id: row.id,
    }
    await productApi.deleteProduct(deleteItem);

    ElMessage.success(`删除${row.name}成功！`);
    getTableData();
};
//填写数据
const writeCosting = (row: EmptyObjectType) => {
    const params: EmptyObjectType = { id: row.id };
    router.push({
        path: '/mainData/product/instance',
        query: params,
    });
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
    state.tableData.param.pageNum = page.pageNum;
    state.tableData.param.pageSize = page.pageSize;
    getTableData();
};
// 拖动显示列排序回调
const onSortHeader = (data: TableHeaderType[]) => {
    state.tableData.header = data;
};
// 页面加载时
onMounted(() => {
    getTableData();
});
</script>

<style scoped lang="scss">
.product-container {
    .product-padding {
        padding: 15px;

        .product {
            flex: 1;
            overflow: hidden;
        }
    }
}
</style>
../../../api/mainData/product